﻿using System;
using System.Net;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Data;
using KPIS.DBM;
using KPIS.GERP.GFMS.MODEL;
using KPIS.GERP.GFMS.APP.App_UI.Commons;
using System.IO;

namespace KPIS.GERP.GFMS.APP.App_UI.Forms
{
    public partial class ExampleMailMerge : System.Web.UI.Page
    {
        Main main = new Main();
        MailMerge mailMerge = new MailMerge();
        DBManager dbManager = new DBManager(SystemInfo._DataProvider, SystemInfo._ConnectionString);

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadDdl();
            }
        }

        protected void cmdGenReport_Click(object sender, EventArgs e)
        {
            string strValue = ddl.SelectedValue;

            if (strValue.Length > 0)
            {
                DataTable dtb = LoadPO(strValue);

                if (dtb.Rows.Count > 0)
                {
                    Dictionary<string, string> fields = new Dictionary<string, string>();

                    if (rblReportType.SelectedValue == "Word")
                    {
                        fields.Add("ContactName", dtb.Rows[0]["ContactName"].ToString());
                        fields.Add("DeliveryDate", (main.ConvertNullDateTime(dtb.Rows[0]["DeliveryDate"]) ?? DateTime.Now).ToLongDateString());

                        Dictionary<string, DataTable> Table = new Dictionary<string, DataTable>();
                        Table.Add("table1", dtb);

                        // แบบต่อ string แล้วขึ้นบรรทัดใหม่
                        /*
                        string strDetails = "";
                        foreach (DataRow dr in dtb.Rows)
                        {
                            strDetails = strDetails + "- " + dr["ItemName"].ToString() + " จำนวน " + dr["Qty"].ToString()
                                + " ราคาหน่วยละ " + dr["Price"].ToString() + " บาท รวมเป็นเงิน " + dr["Amount"].ToString() + " บาท" + System.Environment.NewLine;
                        }

                        fields.Add("Details", strDetails);
                        */

                        Dictionary<string, bool> Areas = new Dictionary<string, bool>();
                        Areas.Add("Area1", Convert.ToInt32(dtb.Rows[0][0]) % 2 > 0);
                        Areas.Add("Area2", Convert.ToInt32(dtb.Rows[0][0]) % 2 == 0);

                        string strTemplatePath = Server.MapPath("~/Reports/Templates/สัญญา.docx");
                        string strSaveAsFileName = string.Format("สัญญา{0}.docx", DateTime.Now.ToString("yyyyMMddHHmmssffff"));
                        string strSaveAsPath = Server.MapPath("~/Reports/Temp/");

                        if (mailMerge.MergeTemplate(strTemplatePath, strSaveAsPath + strSaveAsFileName, fields, Table, null, Areas))
                        {
                            mailMerge.SaveFileToClient(Response, strSaveAsPath, strSaveAsFileName, true);
                        }
                    }
                    else if (rblReportType.SelectedValue == "Excel")
                    {
                        for (int i = 0; i < dtb.Rows.Count; i++)
                        {
                            DataRow dr = dtb.Rows[i];
                            string strRow = (i + 1).ToString();
                            fields.Add(strRow + ":1", dr["ContactName"].ToString());
                            fields.Add(strRow + ":2", (main.ConvertNullDateTime(dr["DeliveryDate"]) ?? DateTime.Now).ToLongDateString());
                            fields.Add(strRow + ":3", dr["Code"].ToString());
                            fields.Add(strRow + ":4", dr["ItemName"].ToString());
                            fields.Add(strRow + ":5", dr["Qty"].ToString());
                            fields.Add(strRow + ":6", dr["Price"].ToString());
                            fields.Add(strRow + ":7", dr["Amount"].ToString());
                        }

                        mailMerge.WriteDicToExcel(Response, fields, "Test", Server.MapPath("~/Reports/Templates/"));
                    }
                    else if (rblReportType.SelectedValue == "ExcelTable")
                    {
                        Dictionary<string, DataTable> dtbs = new Dictionary<string, DataTable>();
                        dtbs.Add("B6", dtb);

                        mailMerge.MergeExcel(Response, Server.MapPath("~/Reports/Templates/TestTemplate.xlsx"), string.Format("Test{0}", DateTime.Now.ToString("yyyyMMddHHmmssffff")), dtbs);
                    }
                }
            }
        }

        #region TempDAL
        protected void LoadDdl()
        {
            string strSQL;
            DataTable dtb = null;

            try
            {
                dbManager.Open();
                dbManager.CreateParameters(1);

                dbManager.AddParameters(0, "@delete_status", SystemInfo._DeleteRecordStatus);

                strSQL = "SELECT PoId, Name"
                    + " FROM IcmPurchaseOrder s"
                    + " WHERE s.RecordStatus not like @delete_status";
                dtb = dbManager.ExecuteDataSet(CommandType.Text, strSQL).Tables[0];
            }
            catch (Exception ex)
            {
                throw (ex);
            }
            finally
            {
                dbManager.Dispose();
            }

            ddl.DataSource = dtb;
            ddl.DataBind();
        }

        protected DataTable LoadPO(string PoId)
        {
            string strSQL;
            DataTable dtb = null;

            try
            {
                dbManager.Open();
                dbManager.CreateParameters(1);

                dbManager.AddParameters(0, "@seq", PoId);

                strSQL = "select po.PoId, po.Code, c.NameTh as ContactName"
                    + ", po.DeliveryDate, res.Name as ItemName"
                    + ", bq.Qty, bq.Price"
                    + ", bq.Qty * bq.Price as Amount"

                    + " from IcmPurchaseOrder po"
                    + " left join IcmPurchaseOrderItem poi on po.PoId = poi.PoId"
                    + " left join IcmBidderQuotation bq on poi.BidderQuoId = bq.BidderQuoId"
                    + " left join IcmPurchaseRequestItem pri on bq.PrItemId = pri.PrItemId"
                    + " left join IcmMasResourceItem res on pri.ResItemId = res.ResItemId"
                    + " left join IcmBidder b on po.BidderId = b.BidderId"
                    + " left join IcmMasContact c on b.ConId = c.ConId"

                    + " where po.PoId = @seq";

                dtb = dbManager.ExecuteDataSet(CommandType.Text, strSQL).Tables[0];
            }
            catch (Exception ex)
            {
                throw (ex);
            }
            finally
            {
                dbManager.Dispose();
            }

            return dtb;
        }
        #endregion
    }
}
